<template>
  <div style="height: 100vh;display: flex; align-items: center; justify-content: center; background-color: #409EFF">
    <div style="display: flex;background-color: white; width: 90%; border-radius: 10px; overflow: hidden">
      <div style="flex: 1">
        <img src="@/assets/sangulogo.png" alt="" style="width: 100%">
      </div>
<!--      上下垂直居中，左右水平居中-->
      <div style="flex: 1;display: flex;align-items: center; justify-content: center">
        <el-form :rules="rules" :model="user" style="width: 50%" ref="loginRef">
          <div style="font-size: 30px;font-weight: bold; text-align: center;margin-bottom: 20px">欢迎登录三谷工具库</div>
          <el-form-item prop="username">
            <el-input prefix-icon="el-icon-user" size="medium" placeholder="请输入账号" v-model="user.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input prefix-icon="el-icon-lock" size="medium" placeholder="请输入密码" v-model="user.password" show-password></el-input>
          </el-form-item>
          <el-form-item prop="code">
            <div style="display: flex">
            <!--@keyup.enter.native="login"-->
              <el-input prefix-icon="el-icon-circle-check" size="medium" placeholder="输入验证码"  style="flex: 1" v-model="user.code"></el-input>
              <div style="flex: 1;height: 36px">
                <valid-code @update:value="getCode"/>
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="isLoad" style="width: 100%" @click="login">
              登录
            </el-button>
          </el-form-item>
          <div style="display: flex">
            <div style="flex: 1">还没有账号？请点击<span style="color: #1890ff; cursor: pointer" @click="$router.push('/register')">注册</span>
            </div>
            <div style="flex: 1;text-align: right"><span style="color: #1890ff; cursor: pointer" @click="handleForgetPass">忘记密码</span></div>
          </div>
        </el-form>
      </div>
    </div>

    <el-dialog title="忘记密码" :visible.sync="forgetPassDialogVis" width="30%">
      <el-form :model="forgetUserForm" label-width="80px" style="padding-right: 20px">
        <el-form-item label="用户名">
          <el-input v-model="forgetUserForm.username" autocomplete="off" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item label="手机号">
          <el-input v-model="forgetUserForm.phone" autocomplete="off" placeholder="请输入手机号"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="forgetPassDialogVis = false">取消</el-button>
        <el-button @click="resetPwd" type="primary">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import ValidCode from "@/components/ValidCode";

export default {
  name: "Login",
  components: {
    ValidCode
  },
  // comments: {
  //   ValidCode
  // },
  data(){
    //自定义验证码校验
    const validateCode = (rule,value,callback) => {
      if (value === ''){
        callback(new Error('请输入验证码'));
      } else if (value.toLowerCase() !== this.code){
        callback(new Error('验证码错误'))
      } else {
        callback();
      }
    };

    return {
      forgetUserForm: {}, //忘记密码的表单
      forgetPassDialogVis: false, //默认false不可见
      code: '', //验证码组件传递来的变量
      user: {
        username: '',
        password: '',
        code: '' //表单里用户输入的
      },
      rules: {
        username: [
          { require: true,message: '请输入账号',trigger: 'blur'} //必填
        ],
        password: [
          { require: true,message: '请输入密码',trigger: 'blur'}
        ],
        code: [
          { trigger: 'blur', validator: validateCode}
        ]
      },
      isLoad: false
    }
  },
  created() {
  },
  methods:{
    //初始化弹窗表单
    handleForgetPass(){
      //本来第二次弹窗会携带第一次填入的数据，这里初始化时覆盖为空
      this.forgetUserForm = {}
      //执行弹窗
      this.forgetPassDialogVis = true
    },
    resetPwd(){
      this.$request.put('/login/forgetPwd',this.forgetUserForm).then(res => {
        if (res.code === '200'){
          this.$message.success("重置密码成功")
          this.forgetPassDialogVis = false
        }else {
          this.$message.error("找回失败："+res.msg)
        }
      })
    },
    getCode(code){
      console.log(code);
      // this.code=code; //即使对象里没有声明code，使用时会自动定义code
      this.code= code.toLowerCase()
    },
    login(){
      this.$refs['loginRef'].validate((valid) => {
        if (valid) {
          //验证通过
          console.log(this.code);
          this.isLoad = true
          this.$request.post('/login/login',this.user).then(res => {
            // console.log(res);
            if (res.code === '200'){
              this.$message.success('登录成功')
              this.$router.push('/')
              localStorage.setItem("userInfo",JSON.stringify(res.data))
            }else {
              this.$message.error(res.msg)
            }
          }).catch(error => {
            // 处理请求失败情况
            //this.$message.error('登录请求失败，请检查网络连接')
            // console.error('Login error:', error)
          }).finally(() => {
            // 无论成功还是失败，都关闭加载动画
            this.isLoad = false
          })
        }
      })
    },
    handleEnterKey(event) {
      if (event.key === 'Enter') {
        this.login();
      }
    }
  },
  mounted() {
    // 添加事件监听器到表单的 DOM 元素
    this.$nextTick(() => {
      const formElement = this.$refs.loginRef.$el;
      formElement.addEventListener('keyup', this.handleEnterKey);
    });
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听器,为避免内存泄露和潜在风险(如组件被销毁而事件监听器还在)
    const formElement = this.$refs.loginRef.$el;
    formElement.removeEventListener('keyup', this.handleEnterKey);
  }
}
</script>

<style scoped>

</style>